﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using System.Windows.Shapes;
using System.ComponentModel;
using Telerik.Windows.Controls.Docking;
using Telerik.Windows.Controls.Animation;

namespace MoneyManager.GUI
{
    /// <summary>
    /// Interaction logic for TransactionUserControl.xaml
    /// </summary>
    public partial class TransactionUserControl : UserControl
    {
        public ObservableCollection<Transaction> Transactions { get { return TransactionManager.Transactions; } }
        public Transaction CurrentTransaction { get; private set; }
        public static ICollectionView TransactionsView { get; private set; }
        public List<String> AllCategoriesName { get; private set; }
        private static Boolean _initialisationFinished = false;

        public TransactionUserControl()
        {
            GUIManager.TransactionWindow = this;
            StyleManager.ApplicationTheme = new Expression_DarkTheme();

            InitializeProperties();

            InitializeComponent();

            if (Transactions.Count > 0)
            {
                TransactionGridView.SelectedItems.Add(Transactions[0]);
                AddEditTransactionWindow.CurrentTransaction = Transactions[0];
            }
            _initialisationFinished = true;
        }

        private void InitializeProperties()
        {
            AllCategoriesName = new List<string>();
            AllCategoriesName.Add("All");
            AllCategoriesName.AddRange(CategoryManager.Categories.Select(c => c.Name).ToList());
            TransactionsView = CollectionViewSource.GetDefaultView(Transactions);
            TransactionsView.Filter = TransactionFilter;
        }

        #region Transaction Filter

        private Boolean TransactionFilter(Object sender)
        {
            if (!_initialisationFinished) return true;

            if (sender is Transaction)
            {
                var t = (Transaction)sender;

                if (
                    AmountMeetsSearchCriteria(t.AmountAbs) &&
                    DateMeetsSearchCriteria(t.Date) &&
                    CategoryMeetsSearchCriteria(t.Category.Name) &&
                    TransactionTypeMeetsSearchCriteria(t.Type) &&
                    AnyTransactionFieldContainsSearchingText(t)
                    ) 
                    return true;
            }

            return false;
        }

        private Boolean AmountMeetsSearchCriteria(Double? amount)
        {
            Double? downAmount = null;
            if (DownAmountTextBox.MaskedText != null && DownAmountTextBox.MaskedText != "")
                downAmount = (Double?)Double.Parse(DownAmountTextBox.MaskedText);
            Double? upAmount = null;
            if (UpAmountTextBox.MaskedText != null && UpAmountTextBox.MaskedText != "")
                upAmount = (Double?)Double.Parse(UpAmountTextBox.MaskedText);

            if (
                (amount >= downAmount && amount <= upAmount) ||
                (amount >= downAmount && upAmount == null) ||
                (downAmount == null && amount <= upAmount) ||
                (downAmount == null && upAmount == null)
                )
                return true;

            return false;
        }

        private Boolean DateMeetsSearchCriteria(DateTime? date)
        {
            DateTime? startDate = StartDatePicker.SelectedDate;
            DateTime? endDate = EndDatePicker.SelectedDate;

            if (
                (date >= startDate && date <= endDate) ||
                (date >= startDate && endDate == null) ||
                (startDate == null && date <= endDate) ||
                (startDate == null && endDate == null)
                )
                return true;

            return false;
        }

        private Boolean CategoryMeetsSearchCriteria(String transactionCategoryName)
        {
            String category = CategoryCombobox.SelectedValue.ToString();

            if (transactionCategoryName == category || category == "All")
                return true;

            return false;
        }

        private Boolean AnyTransactionFieldContainsSearchingText(Transaction t)
        {
            String s = SearchTextBox.Text;

            if (
                t.Category.Name.Contains(s) ||
                t.Amount.ToString().Contains(s) ||
                t.Date.ToShortDateString().Contains(s) ||
                t.Description.Contains(s)
                )
                return true;

            return false;
        }

        private  Boolean TransactionTypeMeetsSearchCriteria(TransactionType type)
        {
            //todo
            return true;
        }

    #endregion  

        private void RadGridView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            var selected = TransactionGridView.SelectedItem as Transaction;
            AddEditTransactionWindow.CurrentTransaction = selected;
        }

        private double _width;
        private double _height;

        private void dock_PaneStateChange(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            RadPane pane = e.OriginalSource as RadPane;
            pane.CanUserPin = true;
            pane.CanFloat = true;
            pane.AutoHideWidth = 290;
            pane.AutoHideHeight = 320;
            ToolWindow window = default(ToolWindow);
            if (pane != null && pane.IsFloating)
            {
                var group = pane.ParentOfType<RadPaneGroup>();
                window = pane.ParentOfType<ToolWindow>();
                //if (window == default(ToolWindow))
                //{
                    //this.Dispatcher.BeginInvoke(() =>
                    //{
                    //    window = pane.ParentOfType<ToolWindow>();
                    //    if (window != null)
                    //    {
                    //        window.Width = this.width;
                    //        window.Height = this.height;
                    //    }
                    //});
               // }
                //else
                //{
                    window.Loaded += new RoutedEventHandler(window_Loaded);
                //}
            }
        }

        void window_Loaded(object sender, RoutedEventArgs e)
        {
            ToolWindow window = sender as ToolWindow;
            window.Width = this._width;
            window.Height = this._height;
        }

        private void RadPaneGroup_GotFocus(object sender, RoutedEventArgs e)
        {
            this._width = 300;
            this._height = 320;
        }

        private void DataChanged(object sender, RoutedEventArgs e)
        {
            TransactionsView.Refresh();
        }

    }
}
